package com.spring.mqtt;

import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Data
@Accessors(chain = true)
@Slf4j
public class MqttTopicUtils {
    String recvTopic;
    String originalTopic;
    String subscribeTopic;

    String[] recvTopicLevels;
    String[] originalTopicLevels;

    String[] subscribeTopicLevels;

    Map<String,Object> recvTopicMap;


    public MqttTopicUtils(String recvTopic, String originalTopic){
        this.recvTopic = recvTopic;
        this.recvTopicLevels = recvTopic.split("/");

        this.originalTopic = originalTopic;
        this.originalTopicLevels =  originalTopic.split("/");

        this.subscribeTopic = originalTopic;

        this.recvTopicMap = new HashMap<>();
        for (int i = 0; i < originalTopicLevels.length; i++) {
            if(originalTopicLevels[i].startsWith("{") && originalTopicLevels[i].endsWith("}")){
                subscribeTopic = subscribeTopic.replace(originalTopicLevels[i],"+");
                String key = originalTopicLevels[i].replace("{", "").replace("}", "");
                this.recvTopicMap.put(key, recvTopicLevels[i]);
            }
        }
        this.subscribeTopicLevels = this.subscribeTopic.split("/");

    }

    public static String getSubscribeTopic(String originalTopic){
        String[] originalTopicLevels =  originalTopic.split("/");
        String subscribeTopic = originalTopic;
        for (String originalTopicLevel : originalTopicLevels) {
            if (originalTopicLevel.startsWith("{") && originalTopicLevel.endsWith("}")) {
                subscribeTopic = subscribeTopic.replace(originalTopicLevel, "+");
            }
        }
        return subscribeTopic;
    }

    public static String setTopic(String topic,Map<String,String> map) {

        String[] levels = topic.split("/");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            for (String level : levels) {
                if (level.startsWith("{") && level.endsWith("}")) {
                    String levelName = level.replace("{","").replace("}","");
                    if(key.equals(levelName)) topic = topic.replace(level, value);
                }
            }
        }

        return topic;
    }


}
